package com.spacing.app;

import java.util.ArrayList;
import java.util.Arrays;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.os.Handler;
import android.speech.tts.TextToSpeech;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.View.OnKeyListener;
import android.view.Window;
import android.view.inputmethod.InputMethodManager;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RatingBar;
import android.widget.TextView;
import android.widget.Toast;

import com.actionbarsherlock.app.SherlockActivity;
import com.senseilearning.english.R;
import com.spacing.app.WordsViewActivity.RowModel;
import com.spacing.app.WordsViewActivity.ViewWrapper;
import com.spacing.app.WordsViewActivity.WordlistAdapter;
import com.spacing.app.data.Chapters;
import com.spacing.app.data.Section;
import com.spacing.app.Spacer;

public class QuizActivity extends SherlockActivity {
	static final String[] letters = new String[] { "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M",
			"N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z" };
	Integer[] order = { 0, 1, 2, 3 };
	Question q;
	Button[] buttons;
	TextView hint_tv;
	TextView answer_tv;
	TextView stack;
	Chapters chapters;
	Spacer spacer;
	int chapter;
	Section section;
	Button next;
	String word;
	String word_compare;
	String[] answer;
	String answer_str;
	int index;
	ArrayAdapter<String> adapter;
	static final String[] special_char = new String[] { " ", "!", "@", "#", "$", "%", "^", "&", "*", "(", ")", "?",
			":", ";", ",", "." };
	EditText input;
	TextView score;
	int count_wrong;
	int count_correct;
	boolean done = false;
	String[] answers;
	String[] words1;
	String[] words2;
	boolean[] correct;
	ArrayList<RowModel> list;

	static boolean bool = true;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
				WindowManager.LayoutParams.FLAG_FULLSCREEN);

		super.onCreate(savedInstanceState);
		setContentView(R.layout.typeit);

		Intent intent = getIntent();
		chapters = (Chapters) intent.getSerializableExtra("chapters");
		chapter = (int) intent.getExtras().getInt("chapter");
		section = (Section) intent.getSerializableExtra("section");
		// spacer = new Spacer(section.getWords(), new SchemaHelper(this),
		// "Quiz");

		answers = new String[section.size()];
		words1 = new String[section.size()];
		words2 = new String[section.size()];
		correct = new boolean[section.size()];

		q = new Question(section);
		hint_tv = (TextView) findViewById(R.id.hint);
		answer_tv = (TextView) findViewById(R.id.answer);
		stack = (TextView) findViewById(R.id.stack);

		// next.setEnabled(false);
		input = (EditText) findViewById(R.id.editText9);
		setQuestion();
		bool = true;
		count_wrong = 0;
		count_correct = 0;

		input.setOnKeyListener(new OnKeyListener() {
			public boolean onKey(View v, int keyCode, KeyEvent event) {
				System.out.println(keyCode);

				if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
					return true;
				} else if ((event.getAction() == KeyEvent.ACTION_UP) && keyCode == KeyEvent.KEYCODE_ENTER) {

					/*
					 * if (!bool) { bool = true; clickNext(); return true; }
					 */
					// next.setEnabled(true);
					checkAnswer();
					bool = false;
					return true;
				}

				return false;
			}
		});

	}

	private void setQuestion() {

		if (!q.done()) {
			setTextStack();
			q.nextQuestion();
			word = q.questions[0][0];
			word_compare = removeAccents(q.questions[0][0].toUpperCase());
			hint_tv.setText(q.questions[1][0]);// + " " + word);
			answer = new String[word.length()];
			Arrays.fill(answer, "__");

			words1[index] = q.questions[1][0];
			words2[index] = q.questions[0][0];

			index++;

			input.setTextColor(getResources().getColor(R.color.black));
			input.setBackgroundColor(getResources().getColor(R.color.white));
			input.setText("");

			// spacer.startOfEventTime = System.currentTimeMillis();
			// Set the start of event time. This is needed if the answer is
			// incorrect.

		} else {
			InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
			imm.hideSoftInputFromWindow(input.getWindowToken(), 0);
			setContentView(R.layout.score);
			v = (ListView) findViewById(R.id.listView1);
			done = true;
			score = (TextView) findViewById(R.id.textViewScore);
			int count_total = count_correct + count_wrong;
			score.setText("Score: " + count_correct + "/" + count_total);

			list = new ArrayList<RowModel>();
			for (int i = 0; i < answers.length; i++) {
				list.add(new RowModel(answers[i], words1[i], words2[i], correct[i]));
			}

			v.setAdapter(new WordlistAdapter(list));

		}
	}

	ListView v;

	private RowModel getModel(int position) {
		return (((WordlistAdapter) v.getAdapter()).getItem(position));
	}

	class WordlistAdapter extends ArrayAdapter<RowModel> {
		WordlistAdapter(ArrayList<RowModel> list) {
			super(QuizActivity.this, R.layout.row_word_quiz, list);
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			View row = convertView;

			ViewWrapper wrapper;

			if (row == null) {

				LayoutInflater inflater = getLayoutInflater();

				row = inflater.inflate(R.layout.row_word_quiz, parent, false);
				wrapper = new ViewWrapper(row);
				row.setTag(wrapper);

			} else {
				wrapper = (ViewWrapper) row.getTag();
			}

			RowModel model = getModel(position);
			wrapper.getLabel().setText(model.getWord1());
			wrapper.getLabel2().setText(model.getWord2());
			if (model.getWord2().equals("")) {
				wrapper.getLabel2().setText(" ");
			}
			if (model.getCorrect()) {
				wrapper.getLabel3().setVisibility(View.GONE);
				wrapper.getImageView().setImageResource(R.drawable.check);
				
			} else {
				wrapper.getLabel3().setText(model.getAnswer());
				wrapper.getImageView().setImageResource(R.drawable.wrong);
			}

			return (row);
		}
	}

	class ViewWrapper {
		View base;
		RatingBar rate = null;
		TextView label = null;
		TextView label2 = null;
		TextView label3 = null;
		ImageView image = null;
			
		ViewWrapper(View base) {
			this.base = base;
		}

		TextView getLabel() {
			if (label == null) {
				label = (TextView) base.findViewById(R.id.word1);
			}

			return (label);
		}

		TextView getLabel2() {
			if (label2 == null) {
				label2 = (TextView) base.findViewById(R.id.word2);
			}
			return (label2);
		}

		TextView getLabel3() {
			if (label3 == null) {
				label3 = (TextView) base.findViewById(R.id.answer);
			}
			return (label3);
		}

		ImageView getImageView() {
			if (image == null) {
				image = (ImageView) base.findViewById(R.id.imageCorrect);
			}
			return (image);
		}
		
	}

	class RowModel {
		String word1;
		String word2;
		String answer;
		boolean correct;

		RowModel(String answer, String word1, String word2, boolean correct) {
			this.word1 = word1;
			this.word2 = word2;
			this.answer = answer;
			this.correct = correct;
		}

		public String getWord1() {
			return word1;
		}

		public String getWord2() {
			return word2;
		}

		public String getAnswer() {
			return answer;
		}

		public boolean getCorrect() {
			return correct;
		}

	}

	public void clickNext(View view) {
		bool = true;
		setQuestion();
		// next.setEnabled(false);
	}

	public void clickNext() {
		setQuestion();
		// next.setEnabled(false);
	}

	private static final String PLAIN_ASCII = "AaEeIiOoUu" // grave
			+ "AaEeIiOoUuYy" // acute
			+ "AaEeIiOoUuYy" // circumflex
			+ "AaOoNn" // tilde
			+ "AaEeIiOoUuYy" // umlaut
			+ "Aa" // ring
			+ "Cc" // cedilla
			+ "OoUu" // double acute
	;

	private static final String UNICODE = "\u00C0\u00E0\u00C8\u00E8\u00CC\u00EC\u00D2\u00F2\u00D9\u00F9"
			+ "\u00C1\u00E1\u00C9\u00E9\u00CD\u00ED\u00D3\u00F3\u00DA\u00FA\u00DD\u00FD"
			+ "\u00C2\u00E2\u00CA\u00EA\u00CE\u00EE\u00D4\u00F4\u00DB\u00FB\u0176\u0177"
			+ "\u00C3\u00E3\u00D5\u00F5\u00D1\u00F1"
			+ "\u00C4\u00E4\u00CB\u00EB\u00CF\u00EF\u00D6\u00F6\u00DC\u00FC\u0178\u00FF" + "\u00C5\u00E5"
			+ "\u00C7\u00E7" + "\u0150\u0151\u0170\u0171";

	/**
	 * remove accented from a string and replace with ascii equivalent
	 */
	public static String removeAccents(String s) {
		if (s == null)
			return null;
		StringBuilder sb = new StringBuilder(s.length());
		int n = s.length();
		int pos = -1;
		char c;
		boolean found = false;
		for (int i = 0; i < n; i++) {
			pos = -1;
			c = s.charAt(i);
			pos = (c <= 126) ? -1 : UNICODE.indexOf(c);
			if (pos > -1) {
				found = true;
				sb.append(PLAIN_ASCII.charAt(pos));
			} else {
				sb.append(c);
			}
		}
		if (!found) {
			return s;
		} else {
			return sb.toString();
		}
	}

	public void setTextStack() {
		stack.setText("woord " + (index + 1) + " van " + answers.length);

	}

	public void correctAnswer() {
		count_correct++;
		/*
		 * input.setTextColor(getResources().getColor(R.color.green));
		 * input.setBackgroundColor
		 * (getResources().getColor(R.color.lightgreen));
		 * input.setText(q.questions[0][0]);
		 */
		// spacer.updateAnswer(true, getCurrentTime());
	}

	public void wrongAnswer() {
		count_wrong++;
		/*
		 * input.setTextColor(getResources().getColor(R.color.red));
		 * input.setBackgroundColor(getResources().getColor(R.color.lightred));
		 * input.setText(q.questions[0][0]);
		 */
		// spacer.updateAnswer(false, getCurrentTime());
	}

	public void checkAnswer() {
		String answer = input.getText().toString();
		answer = removeAccents(answer);
		answer = answer.toLowerCase();
		answer = answer.trim();
		answer = answer.replaceAll(",", "");

		String correct_answer = q.questions[0][0];
		correct_answer = removeAccents(correct_answer);
		correct_answer = correct_answer.toLowerCase();
		correct_answer = correct_answer.replaceAll(",", "");
		correct_answer = correct_answer.trim();

		answers[index - 1] = answer;

		if (answer.equals(correct_answer)) {
			correct[index - 1] = true;
			correctAnswer();
		} else {
			correct[index - 1] = false;
			wrongAnswer();
		}
		clickNext();
	}

	public long getCurrentTime() {
		return System.currentTimeMillis();
	}

	public void clickDone(View v) {

		finish();

	}

	@Override
	public void onBackPressed() {
		if (done) {
			finish();
		} else {
			showDialogQuit();
		}

	}

	private void showDialogQuit() {
		DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				switch (which) {
				case DialogInterface.BUTTON_POSITIVE:
					finish();
					break;

				case DialogInterface.BUTTON_NEGATIVE:
					break;
				}
			}
		};
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setMessage("Weet je zeker dat je wilt stoppen met overhoren?")
				.setPositiveButton(getString(R.string.yes), dialogClickListener)
				.setNegativeButton(getString(R.string.no), dialogClickListener).show();
	}

}